<template>
  <div class="login_box">
    <div class="form_box">
      <div class="logo_box">
        <img src="../assets/logo.png" alt="" />
      </div>
      <el-form ref="loginForm" :model="form" :rules="rules">
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user"
            v-model="form.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            prefix-icon="el-icon-lock"
            v-model="form.password"
          ></el-input>
        </el-form-item>
        <el-form-item class="btn_box">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    login() {
      // 请求登录接口，验证用户名和密码是否正确
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          /*
            注意，async 与 await 必须是父子关系 (await它的第一次函数上必须有async)
          */

          const {
            data: { data, meta },
          } = await this.$http.post("login", this.form);
          // 如果验证失败提示用户登录失败，并阻止后续代码
          if (meta.status !== 200) return this.$message.error("登陆失败");
            // 保存token
            sessionStorage.setItem("token", data.token);
            // 保存用户名
            sessionStorage.setItem("username", data.username);
            // 跳转首页
            this.$router.push("/main");
            this.$message.success("登录成功");
        }
      });
    },
    reset() {
      // elementui 的form表单重置方法
      this.$refs.loginForm.resetFields();
    },
  },
};
</script>
<style lang="less" scoped>
.login_box {
  background-color: #4cf;
  height: 100%;
  .form_box {
    background-color: #fff;
    width: 450px;
    height: 300px;
    border-radius: 5px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 100px 20px 0;
    box-sizing: border-box;
    .btn_box {
      text-align: right;
    }
    .logo_box {
      border: 10px solid #fff;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      background-color: #eee;
      box-shadow: 0 0 10px #ddd;
      overflow: hidden;
      position: absolute;
      left: 50%;
      top: 0;
      transform: translate(-50%, -50%);
      img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
      }
    }
  }
}
</style>